package com.xindaoapp.happypet;

import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.lidroid.xutils.ViewUtils;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.xindaoapp.happypet.activity.BrandActivity;
import com.xindaoapp.happypet.activity.BrandListItem;
import com.xindaoapp.happypet.activity.CatListItem;
import com.xindaoapp.happypet.activity.GoodsClassActivity;
import com.xindaoapp.happypet.activity.GoodsSerachActivity;
import com.xindaoapp.happypet.activity.GradeActivity;
import com.xindaoapp.happypet.activity.MainActivity;
import com.xindaoapp.happypet.activity.NewGoodsActivity;
import com.xindaoapp.happypet.activity.ProductDetailActivity1;
import com.xindaoapp.happypet.activity.SecKillActivity;
import com.xindaoapp.happypet.activity.TuanActivity;
import com.xindaoapp.happypet.activity.UserActivity;
import com.xindaoapp.happypet.activity.WebInfoActivity;
import com.xindaoapp.happypet.api.AddClient;
import com.xindaoapp.happypet.api.Address;
import com.xindaoapp.happypet.bean.Brand;
import com.xindaoapp.happypet.bean.SecKill;
import com.xindaoapp.happypet.bean.SecKill.Data.SecKillGood;
import com.xindaoapp.happypet.bean.ShopBanner;
import com.xindaoapp.happypet.bean.ShopBanner.Banner;
import com.xindaoapp.happypet.bean.ShopBrand;
import com.xindaoapp.happypet.bean.ShopMainCart;
import com.xindaoapp.happypet.fragment.XDBaseFragment;
import com.xindaoapp.happypet.fragments.ShoppingCartFragment;
import com.xindaoapp.happypet.utils.CommonParameter.UserState;
import com.xindaoapp.happypet.utils.CommonUtil;
import com.xindaoapp.happypet.utils.Constants;
import com.xindaoapp.happypet.view.CustomDigitalClock;
import com.xindaoapp.happypet.view.ElasticScrollView;
import com.xindaoapp.happypet.view.ElasticScrollView.OnRefreshListener;
import com.xindaoapp.happypet.view.RollViewPager;

public class ShopFragement extends XDBaseFragment implements OnClickListener {
    private ImageView main_rightmenu;
    // 初始化搜索和banner
    private RelativeLayout rl_search;
    // private ViewPager viewpager;
    private LinearLayout viewpager;
    private TextView description;
    private LinearLayout ll_points;
    private RelativeLayout leimu;
    private RelativeLayout shop_new;
    private RelativeLayout shop_pingfen;
    private RelativeLayout shop_tuan;

    // 尾巴圈品牌馆
    private GridView shop_brand;
    private GridView shop_seckill;

    private LinearLayout seckkill;

    private ElasticScrollView scoller;

    private Context context;
    private ImageView cart_count;

    private List<View> dotLists;

    private DeleteSuccessReceiver receiver;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.shop_fragement, container, false);
        ViewUtils.inject(this, view);
        main_rightmenu = (ImageView) view.findViewById(R.id.main_rightmenu);
        scoller = (ElasticScrollView) view.findViewById(R.id.scoller);
        return view;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        context = getActivity().getApplicationContext();
        initScollerView();
        initViewPager();
        initBrand();
        initClick();
        initSecKill();
        receiver = new DeleteSuccessReceiver();
        context.registerReceiver(receiver, new IntentFilter(Constants.DELETE_CART));
        super.onActivityCreated(savedInstanceState);
    }

    @Override
    public void onResume() {
        if (UserState.isLogged()) {
            initShopCartNum();
        }
        super.onResume();
    }

    private void initScollerView() {
        LinearLayout ll = (LinearLayout) View.inflate(context, R.layout.shop_content, null);
        rl_search = (RelativeLayout) ll.findViewById(R.id.rl_search);
        // viewpager = (ViewPager) ll.findViewById(R.id.shop_viewpager);
        viewpager = (LinearLayout) ll.findViewById(R.id.shop_viewpager);
        description = (TextView) ll.findViewById(R.id.tv_image_description1);
        ll_points = (LinearLayout) ll.findViewById(R.id.ll_points);
        // 购物车
        cart_count = (ImageView) ll.findViewById(R.id.cart_count);
        // 类目
        leimu = (RelativeLayout) ll.findViewById(R.id.shop_leimu);
        // 新品
        shop_new = (RelativeLayout) ll.findViewById(R.id.shop_new);
        shop_pingfen = (RelativeLayout) ll.findViewById(R.id.shop_pingfen);
        // 团购
        shop_tuan = (RelativeLayout) ll.findViewById(R.id.shop_tuan);
        shop_brand = (GridView) ll.findViewById(R.id.shop_brand);
        shop_seckill = (GridView) ll.findViewById(R.id.shop_seckill);
        seckkill = (LinearLayout) ll.findViewById(R.id.seckkill);
        scoller.addChild(ll, 1);
        scoller.setonRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh() {
                initSecKill();
                initViewPager();
                initBrand();
            }
        });


    }

    private SecKillAdapter secAdapter;

    private void initSecKill() {
        AddClient.get(Address.SECKILL, null, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, String content) {
                try {
                    SecKill parse = JSON.parseObject(content, SecKill.class);
                    if (parse.getStatus().equals("1")) {
                        List<com.xindaoapp.happypet.bean.SecKill.Data.SecKillGood> starting =
                                parse.data.starting;
                        if (secAdapter == null) {
                            secAdapter = new SecKillAdapter(starting);
                            shop_seckill.setAdapter(secAdapter);
                        } else {
                            secAdapter.notifyDataSetChanged();
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                scoller.onRefreshComplete();
                super.onSuccess(statusCode, content);
            }

            @Override
            public void onFailure(Throwable error, String content) {
                scoller.onRefreshComplete();
                super.onFailure(error, content);
            }
        });
    }

    private class SecKillAdapter extends BaseAdapter {
        private final List<com.xindaoapp.happypet.bean.SecKill.Data.SecKillGood> starting;

        public SecKillAdapter(List<SecKillGood> starting) {
            super();
            this.starting = starting;
        }

        @Override
        public int getCount() {
            int count = 0;

            if (starting.size() >= 3) {
                count = 3;
            }
            if (starting.size() < 3) {
                count = starting.size();
            }
            return count;
        }

        @Override
        public Object getItem(int position) {
            return starting.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            final ViewHolderSecKill holder;
            if (convertView == null) {
                holder = new ViewHolderSecKill();
                convertView = View.inflate(context, R.layout.shop_seckill, null);
                holder.seckill_pic = (ImageView) convertView.findViewById(R.id.seckill_pic);
                holder.shop_seckill_price =
                        (TextView) convertView.findViewById(R.id.shop_seckill_price);
                holder.remainTime = (CustomDigitalClock) convertView.findViewById(R.id.remainTime);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolderSecKill) convertView.getTag();
            }
            holder.remainTime.setEndTime((formatDate(starting.get(position).end_time)));

            holder.shop_seckill_price
                    .setText(formatPrice(Float.valueOf(starting.get(position).ext_infos.price_ladder
                            .get(0).price)));
            ImageLoader.getInstance().displayImage(starting.get(position).goods_thumb,
                    holder.seckill_pic);
            convertView.setBackgroundColor(Color.WHITE);
            return convertView;
        }
    }

    private String formatPrice(Float a) {
        DecimalFormat df = new DecimalFormat("0.00");
        return df.format(a);
    }

    Handler handler2 = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 10:
                    break;
                default:
                    break;
            }
        };
    };

    public class MyThread implements Runnable {
        @Override
        public void run() {
            while (true) {
                try {
                    Thread.sleep(1000);
                    Message message = new Message();
                    message.what = 10;
                    handler2.sendMessage(message);
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        }
    }

    public static long formatDate(String data) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            return sdf.parse(data).getTime();
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return 0;
    }

    class ViewHolderSecKill {
        ImageView seckill_pic;
        TextView shop_seckill_price;
        CustomDigitalClock remainTime;
    }

    private LinkedList<Brand> brands;
    private BrandAdapter brandadapter;

    private void initBrand() {
        brands = new LinkedList<Brand>();
        RequestParams params = new RequestParams();
        params.put("page", "1");
        params.put("pageSize", "10");
        AddClient.get(Address.SHOPBRAND, params, new AsyncHttpResponseHandler() {
            private LinkedList<Brand> info;

            @Override
            public void onSuccess(int statusCode, String content) {
                try {
                    ShopBrand shop = JSON.parseObject(content, ShopBrand.class);
                    if (shop.getStatus().equals("1")) {
                        if (brands != null && brands.size() > 0) {
                            brands.clear();
                        }
                        info = shop.data.info;
                        brands.add(info.get(0));
                        brands.add(info.get(1));
                        brands.add(info.get(2));
                        brands.add(info.get(3));
                        brands.add(info.get(4));
                        brands.addLast(new Brand("10000",
                                "http://ts.leepet.com/data/brandlogo/1400546559662185358.png",
                                "2222222222"));
                        if (brandadapter == null) {
                            brandadapter = new BrandAdapter();
                            shop_brand.setAdapter(brandadapter);
                            shop_brand.setOnItemClickListener(new OnItemClickListener() {
                                @Override
                                public void onItemClick(AdapterView<?> parent, View view,
                                        int position, long id) {
                                    if (position != brands.size() - 1) {
                                        Intent intent = new Intent(context, BrandListItem.class);
                                        intent.putExtra("brandID", brands.get(position)
                                                .getBrand_id());
                                        intent.putExtra("brandName", brands.get(position)
                                                .getBrand_name());
                                        startActivity(intent);
                                    } else {
                                        Intent i = new Intent(context, BrandActivity.class);
                                        startActivity(i);
                                    }
                                }
                            });
                        } else {
                            brandadapter.notifyDataSetChanged();
                        }

                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                super.onSuccess(statusCode, content);
            }

            @Override
            public void onFailure(Throwable error, String content) {

                super.onFailure(error, content);
            }
        });
    }

    private class BrandAdapter extends BaseAdapter {
        @Override
        public int getCount() {
            return 6;
        }

        @Override
        public Object getItem(int position) {
            return position;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolderBrand holder;
            if (convertView == null) {
                convertView = View.inflate(context, R.layout.shop_brand_item, null);
                holder = new ViewHolderBrand();
                holder.shop_rl = (RelativeLayout) convertView.findViewById(R.id.shop_rl);
                holder.top = (TextView) convertView.findViewById(R.id.shop_brand_item_top);
                holder.brand = (TextView) convertView.findViewById(R.id.shop_brand_item_brand);
                holder.image = (ImageView) convertView.findViewById(R.id.shop_brand_item_image);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolderBrand) convertView.getTag();
            }
            if (position == brands.size() - 1) {
                holder.top.setVisibility(View.GONE);
                holder.brand.setGravity(Gravity.CENTER);
                holder.image.setVisibility(View.GONE);

                LinearLayout ll = (LinearLayout) View.inflate(context, R.layout.brand_more, null);

                holder.shop_rl.setGravity(Gravity.CENTER);
                holder.shop_rl.removeAllViews();
                holder.shop_rl.addView(ll);
                holder.brand.setVisibility(View.GONE);
            } else {
                // holder.top.setText(brands.get(position).getBrand_id());
                holder.brand.setText(brands.get(position).getBrand_name());
                ImageLoader.getInstance().displayImage(brands.get(position).getBrand_logo(),
                        holder.image);
            }

            return convertView;
        }

    }

    private class ViewHolderBrand {
        TextView top;
        TextView brand;
        ImageView image;
        RelativeLayout shop_rl;
    }

    private void initClick() {
        rl_search.setOnClickListener(this);
        leimu.setOnClickListener(this);
        main_rightmenu.setOnClickListener(this);
        shop_new.setOnClickListener(this);
        shop_pingfen.setOnClickListener(this);
        shop_tuan.setOnClickListener(this);
        seckkill.setOnClickListener(this);
        getView().findViewById(R.id.shop_shoppingcar).setOnClickListener(this);
    }

    private List<Banner> banners;
    private boolean isFirst = true;

    private void initViewPager() {
        // final MyPagerAdapter adapter = new MyPagerAdapter();
        AddClient.get(Address.SHOPBANNER, null, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, String content) {
                if (loading != null && loading.getVisibility() == View.VISIBLE) {
                    animation.stop();
                    loading.setVisibility(View.GONE);
                }
                isFirst = false;
                try {
                    ShopBanner banner = JSON.parseObject(content, ShopBanner.class);
                    if (banner.getStatus().endsWith("1")) {
                        banners = banner.getData();
                        List<String> titleList = new ArrayList<String>();
                        List<String> imageUrlList = new ArrayList<String>();
                        if (banners != null && banners.size() > 0) {
                            for (Banner homeBanner : banners) {
                                titleList.add(homeBanner.title);
                                imageUrlList.add(homeBanner.getCoverpath());
                            }
                            prepareData(context, banners);
                            RollViewPager rollViewPager =
                                    new RollViewPager(getActivity(), dotLists,
                                            R.drawable.point_normal, R.drawable.point_enable,
                                            new RollViewPager.MyOnTouchCllickCallBack() {
                                                @Override
                                                public void OnTouchCllick(int position) {
                                                    if (banners.get(position).getType().equals("1")
                                                            && banners.get(position).getEnable()
                                                                    .equals("1")) {
                                                        // 商品详情
                                                        Intent intent =
                                                                new Intent(
                                                                        context,
                                                                        ProductDetailActivity1.class);
                                                        intent.putExtra(
                                                                "productId",
                                                                banners.get(
                                                                        position % banners.size())
                                                                        .getLink());
                                                        startActivity(intent);
                                                    } else if (banners.get(position).getType()
                                                            .equals("2")
                                                            && banners.get(position).getEnable()
                                                                    .equals("1")) {
                                                        // 品牌

                                                        // Intent intent = new Intent(context,
                                                        // WebInfoActivity.class);
                                                        // intent.putExtra("url",
                                                        // "http://www.baidu.com");
                                                        // startActivity(intent);
                                                        Intent intent =
                                                                new Intent(context,
                                                                        BrandListItem.class);
                                                        intent.putExtra("brandName",
                                                                banners.get(position).getLink());
                                                        startActivity(intent);
                                                    } else if (banners.get(position).getType()
                                                            .equals("3")
                                                            && banners.get(position).getEnable()
                                                                    .equals("1")) {
                                                        // 分类详情
                                                        Intent intent =
                                                                new Intent(context,
                                                                        CatListItem.class);
                                                        intent.putExtra("catName",
                                                                banners.get(position).getLink());
                                                        startActivity(intent);
                                                    } else if (banners.get(position).getType()
                                                            .equals("4")
                                                            && banners.get(position).getEnable()
                                                                    .equals("1")) {
                                                        // web
                                                        Intent intent =
                                                                new Intent(context,
                                                                        WebInfoActivity.class);
                                                        intent.putExtra("url", banners
                                                                .get(position).getLink());
                                                        startActivity(intent);
                                                    } else if (banners.get(position).getType()
                                                            .equals("5")
                                                            && banners.get(position).getEnable()
                                                                    .equals("1")) {
                                                        // 关键词搜索
                                                        Intent intent =
                                                                new Intent(context,
                                                                        GoodsSerachActivity.class);
                                                        intent.putExtra("keyword",
                                                                banners.get(position).getLink());
                                                        startActivity(intent);
                                                    }
                                                }
                                            });
                            // viewpager.setAdapter(adapter);
                            rollViewPager.setLayoutParams(new LinearLayout.LayoutParams(
                                    LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
                            rollViewPager.setTitle(description, titleList);
                            rollViewPager.setImageUrl(imageUrlList);
                            rollViewPager.startRoll();
                            viewpager.removeAllViews();
                            viewpager.addView(rollViewPager);
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                super.onSuccess(statusCode, content);
            }

            @Override
            public void onFailure(Throwable error, String content) {
                scoller.onRefreshComplete();
                if (isFirst) {
                    animation.stop();
                    // loading.setVisibility(View.VISIBLE);
                    imageView.setVisibility(View.GONE);
                    load_fail.setVisibility(View.VISIBLE);
                    load_fail.setOnClickListener(new OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            load_fail.setVisibility(View.GONE);
                            initViewPager();
                            initBrand();
                            initClick();
                            initSecKill();
                            imageView.setVisibility(View.VISIBLE);
                            animation.start();
                        }
                    });
                }
                super.onFailure(error, content);
            }
        });
    }

    private void prepareData(Context context, List<Banner> b) {
        dotLists = new ArrayList<View>();
        ll_points.removeAllViews();
        if (b != null && b.size() > 0) {
            for (int i = 0; i < b.size(); i++) {
                LinearLayout.LayoutParams layoutParams =
                        new LinearLayout.LayoutParams(CommonUtil.dip2px(context, 10),
                                CommonUtil.dip2px(context, 10));
                layoutParams.setMargins(5, 0, 5, 0);
                View m = new View(context);
                if (i == 0) {
                    m.setBackgroundResource(R.drawable.point_enable);
                } else {
                    m.setBackgroundResource(R.drawable.point_normal);
                }
                m.setLayoutParams(layoutParams);
                dotLists.add(m);
                ll_points.addView(m);
            }
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.rl_search:
                Intent sreach = new Intent(context, GoodsSerachActivity.class);
                startActivity(sreach);
                break;
            // 商品分类
            case R.id.shop_leimu:
                Intent intent = new Intent(context, GoodsClassActivity.class);
                startActivity(intent);
                break;
            case R.id.main_rightmenu:
                // ClubFragement.openRight();
                if (UserState.isLogged()) {
                    Intent intent1 = new Intent(context, UserActivity.class);
                    startActivity(intent1);
                }
                break;
            case R.id.shop_new:
                Intent shop_new = new Intent(context, NewGoodsActivity.class);
                startActivity(shop_new);
                break;
            case R.id.shop_pingfen:
                Intent shop_pingfen = new Intent(context, GradeActivity.class);
                startActivity(shop_pingfen);
                break;
            case R.id.shop_tuan:
                Intent shop_tuan = new Intent(context, TuanActivity.class);
                startActivity(shop_tuan);
                break;
            case R.id.seckkill:
                Intent seckkill = new Intent(context, SecKillActivity.class);
                startActivity(seckkill);
                break;
            case R.id.shop_shoppingcar:
                if (UserState.isLogged(getActivity())) {
                    Intent mainIntent = new Intent(getActivity(), MainActivity.class);
                    mainIntent.putExtra(Constants.KEY_SKIP_CLASS_NAME,
                            ShoppingCartFragment.class.getCanonicalName());
                    startActivity(mainIntent);
                }
                break;
            default:
                break;
        }
    }

    private void initShopCartNum() {
        RequestParams params = new RequestParams();
        if (UserState.isLogged()) {
            params.put("userID", UserState.getUserUid());
        }
        AddClient.get(Address.CARTLIST, params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, String content) {
                try {
                    ShopMainCart parse = JSON.parseObject(content, ShopMainCart.class);
                    if (parse.getStatus().equals("1")) {
                        if (parse.data == null || parse.data.size() == 0) {
                            new Handler().post(new Runnable() {
                                @Override
                                public void run() {
                                    if (cart_count != null) {
                                        cart_count.setVisibility(View.GONE);
                                    }
                                }
                            });
                        } else {
                            new Handler().post(new Runnable() {
                                @Override
                                public void run() {
                                    if (cart_count != null) {
                                        cart_count.setVisibility(View.VISIBLE);
                                    }
                                }
                            });
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                super.onSuccess(statusCode, content);
            }

            @Override
            public void onFailure(Throwable error, String content) {
                super.onFailure(error, content);
            }
        });
    }

    @Override
    public void onDestroy() {
        context.unregisterReceiver(receiver);
        super.onDestroy();
    }

    private class DeleteSuccessReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            cart_count.setVisibility(View.GONE);
        }
    }
}
